<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>JSDoc: Source: lib/paragraph.js</title>

    <script src="scripts/prettify/prettify.js"> </script>
    <script src="scripts/prettify/lang-css.js"> </script>
    <!--[if lt IE 9]>
      <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
    <link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
    <link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css">
</head>

<body>

<div id="main">

    <h1 class="page-title">Source: lib/paragraph.js</h1>

    



    
    <section>
        <article>
            <pre class="prettyprint source linenums"><code>/**
 * 用于段落评分时的流程控制。&lt;br>
 *
 * @module ChiVoxSDK/Paragraph
 * @author Don Li &lt;kai.li@chivox.com>
 * @licence
 * Copyright (c) 2017 - 2020 ChiVox Inc. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

import cfg             from '../config.json';
import Utils           from '../utils';

import PlayerBuilder   from '../playerbuilder';
import RecorderBuilder from '../recorderbuilder';
import ProgressBar     from '../progressbar';
import Dialog          from '../dialog';


/**
 * 初始化Paragraph实例的默认值。&lt;br/>
 *
 * @name Default_Paragraph_Options
 * @global
 * @constant
 * @property {enum=} mode - 指定Paragraph的模式。可以指定为ChiVoxSDK.MODE.HTML5(默认值) 或 ChiVoxSDK.MODE.FLASH。
 * @property {string=} server - 指定Paragraph的评分服务器地址。默认值: ws://cloud.chivox.com
 * @property {string=} bak_server - 指定Paragraph的评分备份服务器地址。默认值: ''
 * @property {string} appKey - 指定Paragraph的开始评分所使用的appKey（由驰声提供）。**必填**
 * @property {string} sigurl - 指定Paragraph的开始评分前获取sig和timestamp的服务器地址（sig算法由驰声提供）。**必填**
 * @property {boolean=} playDing - 录音前，是否播放"Ding"音频。
 * @property {Object} data - 录音和播放音频所需的参数列表，如下：
 * @property {Object} data.audioUrl - 播放的音频URL。
 * @property {Object} data.serverParams - 录音所需的参数列表，下面描述几个基本的，更多请参考Example或联系驰声提供。
 * @property {Object} data.serverParams.coreType - 录音使用的内核类型。
 * @property {Object} data.serverParams.refText - 录音使用的参考文本。
 * @property {Object} data.serverParams.rank - 录音使用的分制。
 * @property {Object} data.serverParams.userId - 录音的终端用户ID，用于统计和分析用户更多的数据。
 *
 * @property {callback} onInit - 初始化完成后的Callback调用。格式：(code, message) => {}
 * @property {callback} onError - 初始化或运行期间出错时的Callback调用。格式：(error) => {}
 * @property {callback} onReset - 重置后的Callback调用。格式：() => {}
 * @property {callback} onBeforePlay - 播放当前段音频前的Callback调用。格式：(i) => {}
 * @property {callback} onPlay - 开始播放当前段音频时的Callback调用。格式：() => {}
 * @property {callback} onAfterPlay - 当前段音频播放后的Callback调用。格式：(i) => {}
 * @property {callback} onBeforeRecord - 当前段开始录音前的Callback调用。格式：(i) => {}
 * @property {callback} onRecord - 当前段录音开始时的Callback调用。格式：() => {}
 * @property {callback} onAfterRecord - 当前段录音完成后的Callback调用。格式：(i) => {}
 * @property {callback} onScore - 当前段评分结果返回时的Callback调用。格式：(data, partIndex) => {}
 * @property {callback} onBeforeReplay - 当前段回放录音前的Callback调用。格式：(i) => {}
 * @property {callback} onReplay - 回放当前段录音时的Callback调用。格式：() => {}
 * @property {callback} onAfterReplay - 当前段录音回放完成后的Callback调用。格式：() => {}
 */

const _default_options = {
    mode: null,
    server: cfg.server,
    bak_server: '',
    appKey: '', //application key
    sigurl: '', //sig url on server.
    playDing: true, //play 'ding'

    data: {},

    selector: {
        play: "#playParagraph",
        record: "#recordParagraph",
        replay: "#replayParagraph",
        data: "#paragraphData"
    },

    onError: (err) => {}, //onerror handler
    onReset: () => {},

    onBeforePlay: (i) => {},
    onPlay: () => {},
    onAfterPlay: (i) => {},

    onBeforeRecord: (i) => {},
    onRecord: () => {},
    onAfterRecord: (i) => {},
    onScore: (data, partIndex) => {},

    onBeforeReplay: (i) => {},
    onReplay: () => {},
    onAfterReplay: () => {},
};

/**
 * Paragraph类。&lt;br/>&lt;br/>
 *
 * 段落评分语音面板。
 *
 */
class Paragraph {
    /**
     * 创建一个Paragraph实例。
     *
     * @param {Object} options - 初始化参数。格式参见：{@link Default_Paragraph_Options}
     */
    constructor(options) {
        this.options = Utils.extend(options, _default_options, true);

        if (!options.hasOwnProperty('sigurl') || options.sigurl == "") {
            if (options.hasOwnProperty("onError")) { options.onError('param: sigurl is missing!'); }
        } else {
            this.__ele_play   = Utils.find(document, this.options.selector.play);
            this.__ele_record = Utils.find(document, this.options.selector.record);
            this.__ele_replay = Utils.find(document, this.options.selector.replay);

            this.progressbar  = new ProgressBar();
            this.dialog       = new Dialog();           //设备和网络检测面板
            this.dialog.close();

            if (!this.options.mode)
                this.options.mode = Utils.support_h5() ? cfg.mode.HTML5 : cfg.mode.FLASH;

            this.player = ChiVoxSDK.createPlayer(this.options);
            this.bindPlayerEvent();

            this.recorder = ChiVoxSDK.createRecorder(this.options);
            this.bindRecorderEvent();
            this.bindReplayEvent();
        }
    }

    __reset_all(resetRecord) {
        this.player.reset();
        if (resetRecord) {
            this.recorder.reset();
        } else {
            this.recorder.stopRecord();
            this.recorder.stopReplay();
        }

        this.__idx_play     = 0;
        this.__idx_record   = 0;
        this.__idx_replay   = 0;

        this.progressbar.reset();
        Utils.removeClass(this.__ele_play, "playParagraphActive");
        Utils.removeClass(this.__ele_record, "recordParagraphActive");
        Utils.removeClass(this.__ele_replay, "replayParagraphActive");

        this.options.onReset();
    }

    __begin_play_part() {
        if (this.__idx_play &lt; this.options.data.length) {
            this.options.onBeforePlay(this.__idx_play);
            this.player.load({
                url: this.options.data[this.__idx_play].audioUrl,
                success: (code, message) => {
                    this.player.play({
                        onStart: () => { this.options.onPlay(); },
                        onStop: () => {
                            this.options.onAfterPlay(this.__idx_play);
                            this.__idx_play += 1;
                            this.__begin_play_part();
                        }
                    });
                }
            });
        } else {
            this.__idx_play = 0;
            Utils.removeClass(this.__ele_play, "playParagraphActive");
        }
    }

    /** 为Paragraph实例绑定播放事件。*/
    bindPlayerEvent() {
        Utils.bind(this.__ele_play, 'click', (e) => {
            this.__reset_all(true);

            this.__idx_play = 0;
            Utils.addClass(this.__ele_play, "playParagraphActive");
            this.__begin_play_part();
        });
    }

    __begin_record_part() {
        if (this.__idx_record &lt; this.options.data.length) {
            this.options.onBeforeRecord(this.__idx_record);

            let part_data = this.options.data[this.__idx_record];
            let duration  = 2000 + part_data.refText.replace(/^\s+|\s+$/g, '').split(" ").length * 600;
            let params = { coreType: 'en.sent.score', refText: part_data.refText, rank: 4, userId: 'chivox tester' };

            this.recorder.record({
                duration: duration,
                playDing: this.options.playDing,
                serverParams: params,
                onRecordIdGenerated: (code, message) => {},
                onStart: () => { this.options.onRecord(); this.progressbar.start(duration); },
                onStop: () => { this.progressbar.stop(); this.options.onAfterRecord(this.__idx_record); },
                onScore: (data) => {
                    this.options.onScore(data, this.__idx_record);
                    this.__idx_record += 1;
                    this.__begin_record_part();
                },
                onScoreError: () => {
                    this.options.onError('score error');
                    this.options.onAfterRecord(this.__idx_record);
                    this.__idx_record = 0;
                    Utils.removeClass(this.__ele_record, "recordParagraphActive");
                }
            });
        } else {
            this.__idx_record = 0;
            Utils.removeClass(this.__ele_record, "recordParagraphActive");
        }
    }

    /** 为Paragraph实例绑定录音事件。*/
    bindRecorderEvent() {
        Utils.bind(this.__ele_record, 'click', (e) => {
            this.__reset_all(true);

            this.__idx_record = 0;
            Utils.addClass(this.__ele_record, "recordParagraphActive");
            this.__begin_record_part();
        });
    }

    /** 为Paragraph实例绑定录音回放事件。*/
    bindReplayEvent() {
        Utils.bind(this.__ele_replay, 'click', (e) => {
            console.warn('no implements!!!');
        });
    }

    /**
     * 创建一个播放器。
     *
     * @param {Object} options - 创建播放器所需要的参数。
     * @return {Object} - Html5Player或FlashPlayer的实例。
     */
    static createPlayer(options) { return PlayerBuilder.build(options); }

    /**
     * 创建一个录音机。
     *
     * @param {Object} options - 创建录音机所需要的参数。
     * @return {Object} - Html5Recorder或FlashRecorder的实例。
     */
    static createRecorder(options) { return RecorderBuilder.build(options); }
}

export default Paragraph
</code></pre>
        </article>
    </section>




</div>

<nav>
    <h2><a href="index.html">Home</a></h2><h3>Modules</h3><ul><li><a href="module-ChiVoxSDK.html">ChiVoxSDK</a></li><li><a href="module-ChiVoxSDK_flash.html">ChiVoxSDK/flash</a></li><li><a href="module-ChiVoxSDK_html5.html">ChiVoxSDK/html5</a></li><li><a href="module-ChiVoxSDK_lib.html">ChiVoxSDK/lib</a></li><li><a href="module-ChiVoxSDK_Paragraph.html">ChiVoxSDK/Paragraph</a></li><li><a href="module-ChiVoxSDK_score.html">ChiVoxSDK/score</a></li></ul><h3>Classes</h3><ul><li><a href="module-ChiVoxSDK_flash.FlashPlayer.html">FlashPlayer</a></li><li><a href="module-ChiVoxSDK_flash.FlashRecorder.html">FlashRecorder</a></li><li><a href="module-ChiVoxSDK_html5.Html5Player.html">Html5Player</a></li><li><a href="module-ChiVoxSDK_html5.Html5Recorder.html">Html5Recorder</a></li><li><a href="module-ChiVoxSDK_html5-VolumeBar.html">VolumeBar</a></li><li><a href="module-ChiVoxSDK_lib-EnScoreMap.html">EnScoreMap</a></li><li><a href="module-ChiVoxSDK_lib-StatusCode.html">StatusCode</a></li><li><a href="module-ChiVoxSDK_Paragraph-Paragraph.html">Paragraph</a></li><li><a href="module-ChiVoxSDK_score-Char.html">Char</a></li><li><a href="module-ChiVoxSDK_score-CnSentScore.html">CnSentScore</a></li><li><a href="module-ChiVoxSDK_score-CnWordScore.html">CnWordScore</a></li><li><a href="module-ChiVoxSDK_score-EnSentRec.html">EnSentRec</a></li><li><a href="module-ChiVoxSDK_score-EnSentScore.html">EnSentScore</a></li><li><a href="module-ChiVoxSDK_score-EnWordScore.html">EnWordScore</a></li><li><a href="module-ChiVoxSDK_score-Phone.html">Phone</a></li><li><a href="module-ChiVoxSDK_score-Word.html">Word</a></li><li><a href="module-ChiVoxSDK-ChiVoxSDK.html">ChiVoxSDK</a></li><li><a href="module-ChiVoxSDK-ControlPanel.html">ControlPanel</a></li><li><a href="module-ChiVoxSDK-Dialog.html">Dialog</a></li><li><a href="module-ChiVoxSDK-PlayerBuilder.html">PlayerBuilder</a></li><li><a href="module-ChiVoxSDK-ProgressBar.html">ProgressBar</a></li><li><a href="module-ChiVoxSDK-RecorderBuilder.html">RecorderBuilder</a></li></ul><h3>Namespaces</h3><ul><li><a href="public.html">public</a></li><li><a href="Utils.html">Utils</a></li></ul><h3>Global</h3><ul><li><a href="global.html#Default_ChiVoxPlayer_Options">Default_ChiVoxPlayer_Options</a></li><li><a href="global.html#Default_ChiVoxRecorder_Options">Default_ChiVoxRecorder_Options</a></li><li><a href="global.html#Default_ChiVoxSDK_Options">Default_ChiVoxSDK_Options</a></li><li><a href="global.html#Default_Paragraph_Options">Default_Paragraph_Options</a></li><li><a href="global.html#get_sig">get_sig</a></li><li><a href="global.html#tts">tts</a></li></ul>
</nav>

<br class="clear">

<footer>
    Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.5.5</a> on Thu Sep 21 2017 16:38:41 GMT+0800 (CST)
</footer>

<script> prettyPrint(); </script>
<script src="scripts/linenumber.js"> </script>
</body>
</html>
